package com.pospi.xstore.ui.vip_ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.R;
import com.pospi.xstore.dto.CouponsBeen;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.pay_ui.PayActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.SaveOrderInfo;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class CountponsActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    @Bind(R.id.yhq_list)
    ListView yhq_list;
    @Bind(R.id.bt_search)
    TextView bt_search;

    List<CouponsBeen> beens = new ArrayList<>();
    private List<CouponsBeen> couponsBeens;
    private MyAdapter adapter;
    private boolean isChoose = false;
    private String vipid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_countpons);
        ButterKnife.bind(this);
        setTitle("可用优惠券");
        vipid = getIntent().getStringExtra("vipid");

        adapter = new MyAdapter();
        yhq_list.setAdapter(adapter);
        yhq_list.setOnItemClickListener(this);
        bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CountponsActivity.this, PayActivity.class);
                intent.putExtra("yhq",getyhq() );
                startActivity(intent);

            }
        });
        getNet();


    }
    private CouponsBeen getyhq(){
        CouponsBeen coup = new CouponsBeen();
        for (CouponsBeen been : beens) {
            if (been.isChoose()) {
                coup = been;
            }
        }
        return coup;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        if (beens.get(i).isChoose()) {
            beens.get(i).setChoose(false);

        } else {
            beens.get(i).setChoose(true);
            for (CouponsBeen been : beens) {
                if (!beens.get(i).getId().equals(been.getId())) {
                    been.setChoose(false);
                }

            }
        }
        adapter.notifyDataSetChanged();
    }

    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return beens.size();
        }

        @Override
        public Object getItem(int i) {
            return beens.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(CountponsActivity.this).inflate(R.layout.coupons_item, null);
                holder.je = view.findViewById(R.id.tv_je);
                holder.tj = view.findViewById(R.id.tv_tj);
                holder.rq = view.findViewById(R.id.tv_rq);
                holder.iv = view.findViewById(R.id.iv_select);
//                holder.tv_edqr = view.findViewById(R.id.tv_edqr);
                view.setTag(holder);

            } else {
                holder = (Holder) view.getTag();
            }
            DecimalFormat decimalFormat = new DecimalFormat("######.##########");
            holder.je.setText(decimalFormat.format(Double.parseDouble(beens.get(i).getDenomination())));
            holder.tj.setText("无门槛优惠券");
            String srq = beens.get(i).getStartt();
            String erq = beens.get(i).getEndt();
            holder.rq.setText("使用时间：" +srq.substring(srq.length()-5,srq.length())+"~"+erq.substring(erq.length()-5,erq.length()));
//            holder.tv_edqr.setText("截止日期：" + beens.get(i).getEndt());
            if (beens.get(i).isChoose()) {
                holder.iv.setVisibility(View.VISIBLE);
            } else {
                holder.iv.setVisibility(View.INVISIBLE);
            }


            return view;
        }

        class  Holder{
            TextView je;
            TextView tj;
            TextView rq;
            TextView tv_edqr;
            ImageView iv;
        }
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    beens.clear();
                    beens.addAll(couponsBeens);
                    if (beens.size() == 0) {
                        Toast.makeText(CountponsActivity.this, "很抱歉，无可用优惠券", Toast.LENGTH_SHORT).show();
                    }
                    adapter.notifyDataSetChanged();
                    break;
                case 3:
                    close();
                    Toast.makeText(CountponsActivity.this, "获取异常", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };


    private void getNet(){
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "vip.vvip");
        params.put("fun", "getusercoupon");
        params.put("vid", vipid);
        Log.i("data", params.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("data", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    if (object.getString("errCode").equals("100")) {
                        JSONArray array = object.getJSONArray("result");
                        couponsBeens = new Gson().fromJson(array.toString(), new TypeToken<List<CouponsBeen>>() {
                        }.getType());
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = 3;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });

    }
}
